Skip to main content

22.02.09 - Types and Classes

A type is a name for a collection of related. Basic type Bool contains two logic values True and False

Type Error - Applying a function to one or more arguments of the wrong type

Types in Haskell

  • Expression e would produce a value of type t, then e has type t
    • e :: t
  • Type inference - Calculates the type of any expression
  • Errors found at compile time to makes programs safer and faster
  • :type calculates the type of an expression without evaluating it

Basic Types

Bool - Logical Values Char - Single Characters String - Strings of characters Int - Integer Numbers Float - Floating-point numbers

List Types

  • A list is a sequence of values of the same type
  • [t] is the type of lists with elements of type t
  • The type of a list says nothing about its length
  • Type of the elements is unrestricted, can have lists of listst
  • Heterogeneous - Can only contain elements of the same type

Tuple Types

A sequence of values of different types

(False, 'a', True) :: (Bool,Char,Bool)
  • The type of a tuple encodes its size
  • The type of the components is unrestricted

Function Types

Function is a mapping from values of one type to values of another type

even :: Int -> Bool

General case t1 \to t2 is the type of functions that map values of type t1 to values to type t2 The argument and result types are unrestricted

Curried Functions

Functions with multiple arguments are also possible by returning functions as results

  • add and add` produce the same final result, but add` takes them one at a time
  • Functions that take their arguments one at a time are called curried function
  • Functions with more than two arguments can be curried by returning nested Functions

Curried functions are more flexible than functions on tuples, because useful functions can often be made by partially applying a curried function

Currying Contentions

To avoid excess parentheses when using curried functions, 2 simple conventions:

  • -> associates to the right
  • As a consequence, it is then natural for function application to associate to the left
  • mult x y z means (mult x) y) z

Polymorphic Functions

Function is called polymorphic ("of many forms") if its type contains one or more type variables

  • Type variables can be instantiated to different types in different circumstances
  • Type variables must begin with a lower-case letter, usually named a,b,c, etc Polymorphic: The type has a type variable such as 'a' Instantiate: Process of making an instance of an object using the class definition

Overloaded Functions

Polymorphic function is called overloaded if its type contains one or more class constraints

  • Can be instantiated to any types that satisfy the constraints
  • 3 types classes
    • Num - Numeric types
    • Eq - Equality types
    • Ord - Ordered types